import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:intl/intl.dart';
import 'package:redux/redux.dart';
import 'package:stock_check/common/dao/DataResult.dart';
import 'package:stock_check/common/dao/UserDao.dart';
import 'package:stock_check/common/db/ITModel.dart';
import 'package:stock_check/common/db/InstitutionModel.dart';
import 'package:stock_check/common/db/SqliteManage.dart';
import 'package:stock_check/common/http/Api.dart';
import 'package:stock_check/common/http/HttpManager.dart';
import 'package:stock_check/common/model/ITAsset.dart';
import 'package:stock_check/common/model/checkITDeviceItem.dart';
import 'package:stock_check/common/model/checkITDeviceItemDetail.dart';
import 'package:stock_check/common/model/checkInstitutionDetail.dart';
import 'package:stock_check/common/model/institutionAsset.dart';
import 'package:stock_check/common/redux/CheckDevicesReducer.dart';
import 'package:stock_check/common/redux/reduxStore.dart';
import 'package:stock_check/common/utils/CommonUtils.dart';

/// 各项任务
class WorksDao{
  // 提交IT资产信息
  static Future<bool> submitITAssetDetail(CheckITDeviceItemDetail detail)async{
    var res;
    if(detail.curStartTimeStr.isEmpty){
      detail.curStartTimeStr = CommonUtils.getCurrentTime();
    }
    Map<String,CheckITDeviceItemDetail> map = {
      "recordDetail":detail
    };
    DataResult result = await UserDao.getUserInfoLocal();
    detail.userId = result.data.id;
    try{
      Dio dio = new Dio(Options(
        baseUrl: Api.baseUrl
      ));
      FormData formData = new FormData.from({
        "detail": json.encode(map),
      });
      res = await dio.post(Api.submitITCheckItemUrl,data:formData);
      return json.decode(res.data)['resultValue'];
    }catch(e){
      Fluttertoast.showToast(msg:e.toString());
      return false;
    }
  }

  // 提交设备资产信息
  static Future<bool> submitInstitutionAssetDetail(CheckInstitutionDetail detail)async{
    var res;
    if(detail.curStartTimeStr.isEmpty){
      detail.curStartTimeStr = CommonUtils.getCurrentTime();
    }
    Map<String,CheckInstitutionDetail> map = {
      "recordDetail":detail
    };
    DataResult result = await UserDao.getUserInfoLocal();
    detail.userId = result.data.id;
    try{
      Dio dio = new Dio(Options(
        baseUrl: Api.baseUrl
      ));
      FormData formData = new FormData.from({
        "detail": json.encode(map),
      });
      res = await dio.post(Api.submitInstitutionCheckItemUrl,data:formData);
      return json.decode(res.data)['resultValue'];
    }catch(e){
      Fluttertoast.showToast(msg:e.toString());
      return false;
    }
  }

  //通过id保存更新后的IT资产信息
  static Future<int> saveITAssetInfo(ITAsset itAsset, int recordId) async{
    for(int i = 0;i<itAsset.itemList.length;i++){
      if(itAsset.itemList[i].status==1){ // 如果是正常的，直接将标准答案填入解释
        itAsset.itemList[i].explain = itAsset.itemList[i].standardContent;
      }
    }
    CheckITDeviceItemDetail cd =  await findITAssetsDetailByRecordID(recordId);
    for(int i=0;i<cd.assetsList.length;i++){
      if(cd.assetsList[i].assetId == itAsset.assetId){
        cd.assetsList[i] = itAsset;
        break;
      }
    }
    return await saveITAssetsDetailByRecordID(cd, recordId);
  }
  //通过id保存更新后的设备资产信息
  static Future<int> saveInstitutionAssetInfo(InstitutionAsset institutionAsset, int recordId) async{
    for(int i = 0;i<institutionAsset.itemList.length;i++){
      if(institutionAsset.itemList[i].status==1){ // 如果是正常的，直接将标准答案填入解释
        institutionAsset.itemList[i].explain = institutionAsset.itemList[i].standardContent;
      }
    }
    CheckInstitutionDetail cd =  await findInstitutionAssetsDetailByRecordID(recordId);

    // 更新保存顺序
    var maxId = 0;
    for(int i=0;i<cd.assetsList.length;i++){
      if(maxId<cd.assetsList[i].curOrder){
        maxId = cd.assetsList[i].curOrder;
      }
    }
    maxId +=1;
    for(int i=0;i<cd.assetsList.length;i++){
      if(cd.assetsList[i].assetId == institutionAsset.assetId){
        if(institutionAsset.curOrder==0){
          institutionAsset.curOrder = maxId;
        }
        cd.assetsList[i] = institutionAsset;
        break;
      }
    }
    return await saveInstitutionsDetailByRecordID(cd, recordId);
  }

  static String getCurrentTime(){
    final formatter = new DateFormat('yyyy-MM-dd');
    String updateTime = formatter.format(DateTime.now());
    return updateTime;
  }

  // 根据记录ID获取到IT资产信息
  static Future<CheckITDeviceItemDetail> findITAssetsDetailByRecordID(int recordId)async{
    DataResult result =  await getLocalNeedCheckITDevicesDetailList(getCurrentTime());
    if(result.result){
      List<CheckITDeviceItemDetail> list = result.data;
      for(int i=0;i<list.length;i++){
        if(list[i].recordId == recordId){
          return list[i];
        }
      }
    }
    return null;
  }

  // 根据记录ID获取到设施资产信息
  static Future<CheckInstitutionDetail> findInstitutionAssetsDetailByRecordID(int recordId)async{
    DataResult result =  await getLocalNeedInstitutionDetailList(getCurrentTime());
    if(result.result){
      List<CheckInstitutionDetail> list = result.data;
      for(int i=0;i<list.length;i++){
        if(list[i].recordId == recordId){
          return list[i];
        }
      }
    }
    return null;
  }

  // 保存变更过的IT资产信息
  static Future<int> saveITAssetsDetailByRecordID(CheckITDeviceItemDetail needSave,int recordId)async{
    String currentTime = getCurrentTime();
    DataResult result =  await getLocalNeedCheckITDevicesDetailList(currentTime);
    List<CheckITDeviceItemDetail> list = result.data;
    for(int i=0;i<list.length;i++){
      if(list[i].recordId == recordId){
        list[i] = needSave;
        break;
      }
    }

    DataBase dataBase = new DataBase();
    ITModel itModel = new ITModel();
    itModel.updateTime = currentTime;
    itModel.jsonTxt = json.encode(list);
    // 存储到本地
    return await dataBase.updateITModel(itModel);
  }

  // 保存变更过的设施资产信息
  static Future<int> saveInstitutionsDetailByRecordID(CheckInstitutionDetail needSave,int recordId)async{
    String currentTime = getCurrentTime();
    DataResult result =  await getLocalNeedInstitutionDetailList(currentTime);
    List<CheckInstitutionDetail> list = result.data;
    for(int i=0;i<list.length;i++){
      if(list[i].recordId == recordId){
        list[i] = needSave;
        break;
      }
    }

    DataBase dataBase = new DataBase();
    InstitutionModel model = new InstitutionModel();
    model.updateTime = currentTime;
    model.jsonTxt = json.encode(list);
    // 存储到本地
    return await dataBase.updateInstitutionModel(model);
  }

  // 检查该资产是否已下载
  static bool _checkLocalData(List<dynamic> list,CheckITDeviceItem item) {
      for(var i=0;i<list.length;i++)
        if(list[i].recordId == item.recordId)
          return true;
      return false;
  }

  // 获取等待巡检的IT设备列表
  static Future<DataResult> getNeedCheckITDevicesList(int deptId,String updateTime) async{
    try{
      var res = await HttpManager.netFetch(Api.itCheckRecordListUrl, {'deptId':deptId});
      List<CheckITDeviceItem> list = new List();
      var jsonList = json.decode(res.data);
      DataResult data = await getLocalNeedCheckITDevicesDetailList(updateTime);
      for(int i=0;i<jsonList.length;i++){
        CheckITDeviceItem ck = CheckITDeviceItem.fromJson(jsonList[i]);
        if(data==null){
          ck.ifDownloadStr = '未下载';
        } else if(!data.result||!_checkLocalData(data.data,ck)){
          ck.ifDownloadStr = '未下载';
        }
        ck.check = false;
        list.add(ck);
      }
      return DataResult(list,true);
    }catch(e){
      return DataResult(null,false);
    }
  }

  // 获取等待巡检的设施设备列表
  static Future<DataResult> getNeedCheckInstitutionsList(int deptId,String updateTime) async{
    try{
      var res = await HttpManager.netFetch(Api.institutionCheckRecordListUrl, {'deptId':deptId});
      DataResult data = await getLocalNeedInstitutionDetailList(updateTime);
      List<CheckITDeviceItem> list = new List();
      var jsonList = json.decode(res.data);
      for(int i=0;i<jsonList.length;i++){
        CheckITDeviceItem ck = CheckITDeviceItem.fromJson(jsonList[i]);
        if(data!=null){
          if(!data.result||!_checkLocalData(data.data, ck)) {
            ck.ifDownloadStr = '未下载';
          }
        }else{
          ck.ifDownloadStr = '未下载';
        }
        ck.check = false;
        list.add(ck);
      }
      return DataResult(list,true);
    }catch(e){
      return DataResult(null,false);
    }

  }

  // IT类资产下载
  static Future<CheckITDeviceItemDetail> downloadITCheckItemByRecordID(int recordId) async {
    var res = await HttpManager.netFetch(Api.downloadITCheckItemUrl, {'recordId':recordId});
    var data = json.decode(json.decode(res.data)['t']);
    CheckITDeviceItemDetail cd = CheckITDeviceItemDetail.fromJson(data['recordDetail']);
    return cd;
  }

  // 设施类资产下载
  static downloadInstitutionByRecordID(int recordId) async {
    var res = await HttpManager.netFetch(Api.downloadInstitutionCheckItemUrl, {'recordId':recordId});
    var data = json.decode(json.decode(res.data)['t']);
    CheckInstitutionDetail ci = CheckInstitutionDetail.fromJson(data['recordDetail']);
    return ci;
  }

  // 获取本地下载的待巡检IT设备列表
  static Future<DataResult> getLocalNeedCheckITDevicesDetailList(String updateTime) async{
    DataBase dataBase = new DataBase();
    ITModel itModel = await dataBase.getOneITByUpdateTime(updateTime);
    if(itModel!=null&&itModel.updateTime!=null&&itModel.jsonTxt!=null){
      String itsStr = itModel.jsonTxt;
      List<CheckITDeviceItemDetail> list = new List();
      if(itsStr!=null){
        var jsonList = json.decode(itsStr);
        for(int i=0;i<jsonList.length;i++){
          list.add(CheckITDeviceItemDetail.fromJson(jsonList[i]));
        }
        return DataResult(list,true);
      }
    }else{
      return DataResult(null,false);
    }
  }

  // 获取本地下载的待巡检设施列表
  static Future<DataResult> getLocalNeedInstitutionDetailList(String updateTime) async{
    DataBase dataBase = new DataBase();
    InstitutionModel model = await dataBase.getOneInstitutionByUpdateTime(updateTime);
    if(model!=null){
      String itsStr = model.jsonTxt;
      List<CheckInstitutionDetail> list = new List();
      if(itsStr!=null){
        var jsonList = json.decode(itsStr);
        for(int i=0;i<jsonList.length;i++){
          list.add(CheckInstitutionDetail.fromJson(jsonList[i]));
        }
        return DataResult(list,true);
      }
    }else{
      return DataResult(null,false);
    }
  }

  // 根据ID删除IT设备数据
  static deleteITAssetDetailByRecordID(BuildContext context,CheckITDeviceItemDetail itDetail) async{
    // 首先删除全局数据
    Store<StockState> store = StoreProvider.of(context);
    List<CheckITDeviceItem> list =  store.state.worksInfo.checkITDevices;
    for(int i=0;i<list.length;i++){
      if(list[i].recordId == itDetail.recordId){
        list.removeAt(i);
      }
    }
    store.dispatch(UpdateCheckITDevicesAction(checkITDeviceItems: list));


    String currentTime = getCurrentTime();
    DataResult result =  await getLocalNeedCheckITDevicesDetailList(currentTime);
    List<CheckITDeviceItemDetail> detailList = result.data;
    for(int i=0;i<detailList.length;i++){
      if(detailList[i].recordId == itDetail.recordId){
        detailList.removeAt(i);
        break;
      }
    }

    DataBase dataBase = new DataBase();
    ITModel itModel = new ITModel();
    itModel.updateTime = currentTime;
    itModel.jsonTxt = json.encode(detailList);
    // 存储到本地
    return await dataBase.updateITModel(itModel);
  }

  // 根据id删除设备数据
  static deleteInstitutionsDetailByRecordID(BuildContext context,CheckInstitutionDetail institutionDetail) async{
    //首先删除全局数据
    Store<StockState> store = StoreProvider.of(context);
    List<CheckITDeviceItem> list =  store.state.worksInfo.institutions;
    for(int i=0;i<list.length;i++){
      if(list[i].recordId == institutionDetail.recordId){
        list.removeAt(i);
      }
    }
    store.dispatch(UpdateCheckInstitutionsAction(checkInstitutionItems: list));

    String currentTime = getCurrentTime();
    DataResult result =  await getLocalNeedInstitutionDetailList(currentTime);
    List<CheckInstitutionDetail> detailList = result.data;
    for(int i=0;i<detailList.length;i++){
      if(detailList[i].recordId == institutionDetail.recordId){
        detailList.removeAt(i);
        break;
      }
    }

    DataBase dataBase = new DataBase();
    InstitutionModel model = new InstitutionModel();
    model.updateTime = currentTime;
    model.jsonTxt = json.encode(detailList);
    // 存储到本地
    return await dataBase.updateInstitutionModel(model);
  }
}